<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Models\Address;
use App\Transformers\AddressTransformer;
use Illuminate\Http\Request;

class AddressController extends BaseController
{
    /**
     * 地址列表
     */
    public function index(Request $request)
    {
        $mac_address = $request->input('mac_address');
        $status = $request->input('status');
        $note = $request->input('note');

        $user = auth('api') ->user();
        $address = $user
            ->address()
            ->when($mac_address,function ($query) use ($mac_address){
                $query->where('mac_address', 'like', "%$mac_address%");
            })
            ->when($status,function ($query) use ($status){
                $query->where('status', $status);
            })
            ->when($note,function ($query) use ($note){
                $query->where('note', 'like', "%$note%");
            })
            ->paginate(20);

        return $this->response->paginator($address, new AddressTransformer());
    }

    /**
     * 添加地址
     */
    public function store(Request $request)
    {
        $request->validate([
           'mac_address' => 'required'
        ],[
            'mac_address.required' => '局域网地址不能为空'
        ]);
        $user = auth('api') ->user();
        $request->offsetSet('user_id', $user->id);
        $request->offsetSet('created_at', now());
        $request->offsetSet('updated_at', now());
//        批量赋值
        Address::create($request->all());

        return $this->response->created();
    }

    /**
     * 更新地址
     */
    public function update(Request $request, Address $address)
    {
        $request->validate([
            'mac_address' => 'required'
        ],[
            'mac_address.required' => '局域网地址不能为空'
        ]);

//        批量赋值
        $address->update([
            'mac_address' => $request->input('mac_address'),
            'note' => $request->input('note') ? $request->input('note') : null,
            'updated_at' => now()
        ]);
        return $this->response->noContent();
    }

    /**
     * 删除地址
     */
    public function destroy(Address $address)
    {
        $address->delete();
        return $this->response->noContent();
    }

    /**
     * 地址状态
     */
    public function status(Address $address)
    {
        $address->status = $address->status == 0 ? 1 : 0;
        $address->save();

        return $this->response->noContent();
    }

}
